package com.lvcoding.auth2.redis.jdbc.security;

import com.lvcoding.auth2.redis.jdbc.domain.SysUser;
import com.lvcoding.auth2.redis.jdbc.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wuyanshen
 * @description 用户认证业务类
 * @date 2022-02-18 下午10:52
 */
@RequiredArgsConstructor
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserService.queryByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("user"));

        return new User(sysUser.getUsername(), sysUser.getPassword(), true, true, true, true, authorities);
    }
}
